package com.xxxx.yoyo.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xxxx.yoyo.bean.Goods;
import com.xxxx.yoyo.bean.Order;
import com.xxxx.yoyo.bean.User;
import com.xxxx.yoyo.service.IGoodsService;
import com.xxxx.yoyo.service.IOrderService;
import com.xxxx.yoyo.service.impl.GoodsServiceImpl;
import com.xxxx.yoyo.service.impl.OrderServiceImpl;

/**
 * Servlet implementation class DeleteGoodsFromOrderServlet
 */
@WebServlet("/index/delete")
public class DeleteGoodsFromCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private IGoodsService goodsService = new GoodsServiceImpl();
	private IOrderService orderService = new OrderServiceImpl();
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//获取session,session的有效期是30分钟,30分钟后session会失效,失效的后果就是session中的数据被销毁.
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		if(user == null) {//session失效了, 需要重新登录
			response.getWriter().append("login");
		}else {//没失效, session中的user,order都还存在
			//获取虚拟订单
			Order order = (Order)session.getAttribute("order");
			
			//获取前端页面传递过来的参数goodid
			String goodsIdStr = request.getParameter("goodid");
			int goodsId = Integer.parseInt(goodsIdStr);
			
			//根据宠物id获取宠物
			Goods goods = goodsService.getGoodsById(goodsId);
			
			//从订单中删除购买项
			boolean isEmpty = orderService.deleteGoodsFromOrder(goods, order);
			if(isEmpty) {
				session.removeAttribute("order");
			}
			response.getWriter().append("ok");
		}
	}

}
